﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.IO;

namespace KeyboardImageViewer
{
    /// <summary>
    /// Interaction logic for RenameBox.xaml
    /// </summary>
    public partial class RenameBox : Window
    {
        string initialPath;
        private ImageUserData userData;

        public RenameBox(MainWindow window)
        {
            this.Owner = window;
            this.userData = ImageListControl.CurrentImageData;

            InitializeComponent();

            this.initialPath = ImageManager.CurrentImageName;
            this.renameText.Text = Path.GetFileName(initialPath);

            this.renameText.SelectionStart = 0;
            this.renameText.SelectionLength = 0;

            this.renameText.Focus();

            if (userData.Tags == null || userData.Tags.Count == 0)
            {
                this.autoName.IsEnabled = false;
            }
        }

        private void RenameClick(object sender, RoutedEventArgs e)
        {
            EditOperations.RenameCurrentImage(this.renameText.Text);
            this.DialogResult = true;
        }

        private void AutoNameClick(object sender, RoutedEventArgs e)
        {
            string extension = Path.GetExtension(this.initialPath);
            string initialFileName = Path.GetFileName(this.initialPath);
            string folder = this.initialPath.Substring(0, this.initialPath.Length - initialFileName.Length);

            string newNameBase = string.Join("-", this.userData.Tags.ToArray());

            string newNameCandidate = newNameBase + extension;

            if (!File.Exists(Path.Combine(folder, newNameCandidate)))
            {
                this.renameText.Text = newNameCandidate;
                return;
            }

            for (int i = 1; i < 50; i++)
            {
                newNameCandidate = newNameBase + "-" + i + extension;
                if (!File.Exists(Path.Combine(folder, newNameCandidate)))
                {
                    this.renameText.Text = newNameCandidate;
                    return;
                }
            }

            this.renameText.Text = newNameBase + "-" + GetRandomString(8) + extension;
        }

        private static string GetRandomString(int length)
        {
            string randomCharacters = "0123456789abcdefghijklmnopqrstuvwxyz";
            StringBuilder builder = new StringBuilder();
            Random rand = new Random();

            for (int i = 0; i < length; i++)
            {
                builder.Append(randomCharacters[rand.Next(randomCharacters.Length)]);
            }

            return builder.ToString();
        }
    }
}
